package com.li.o2oSystem.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.o2oSystem.cache.JedisUtil;
import com.li.o2oSystem.dao.AreaDao;
import com.li.o2oSystem.entity.Area;
import com.li.o2oSystem.exceptions.AreaOperationException;
import com.li.o2oSystem.service.AreaService;
@Service
public class AreaServiceImpl implements AreaService {
	//自动注入
	@Autowired
	private AreaDao areaDao;
	//注入jedis工具类
	@Autowired
	private JedisUtil.Keys jedisKeys;
	@Autowired
	private JedisUtil.Strings jedisStrings;
	
	@Transactional
	public List<Area> getAreaList() {
		String key = AREALISTKEY;
		List<Area> areaList = null;
		//使用jackson
		ObjectMapper mapper = new ObjectMapper();
			if(!jedisKeys.exists(key)){//判断jedis中是否存在key,如果不存在,则从数据库查询
				areaList = areaDao.queryArea();
				//将区域列表信息转换为String
				String jsonString;
				try {
					jsonString = mapper.writeValueAsString(areaList);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
					throw new AreaOperationException("json数据处理异常");
				}
				jedisStrings.set(key, jsonString);
			}
			else{	//如果已经存在
				String jsonString = jedisStrings.get(key);//从redis中获取值
				JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class);
				try {
					areaList = mapper.readValue(jsonString, javaType);//将String转换为Java对象
				} catch (IOException e) {
					e.printStackTrace();
					throw new AreaOperationException("json字符串转Java对象异常：");
				}
			}
		return areaList;
	}
}
/**
 *	①在AreaService 注入JedisUtil中的两个内部类
 *	②定义区域列表字段arealist，字符串 (作为final字段，定义在接口中)
 *	③将定义的字段作为key，
 *	④判断是否存在key，不存在则从数据库中查询
 *	⑤使用Jackjson将区域列表转换为json字符串，
 *	⑥使用jedisStrings设置进redis中
 *	⑦如果redis中存在，则调用jedisStrings根据key取出数据
 *	⑧使用Jackson将json字符串装换为Java对象，
 *	⑨返回区域列表数据
 */
